package com.pig4cloud.pig.module.controller.electric;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.OkHttpClientUtil;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.electric.ElectricMeter;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.estate.EstateRoom;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.service.electric.IElectricMeterService;
import com.pig4cloud.pig.module.service.electric.IElectricOrderService;
import com.pig4cloud.pig.module.service.estate.IEstateRoomService;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 水电Controller
 *
 * @author ruoyi
 * @date 2022-09-01
 */
@Validated
@Api(value = "水电控制器", tags = {"水电管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/devices/meter")
public class ElectricMeterController {

    private final IElectricMeterService electricMeterService;
    private final IEstateRoomService estateRoomService;
	private final IEstateService estateService;
	private final IPropertyService propertyService;
	private final IElectricOrderService electricOrderService;

	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

	/**
     * 查询水电列表
     */
    @ApiOperation("查询水电列表")
    @PreAuthorize("@pms.hasPermission('module:meter:list')")
    @GetMapping("/list")
    public TableDataInfo<ElectricMeter> list(@Validated ElectricMeter electricMeter) {
        QueryWrapper<ElectricMeter> qw = new QueryWrapper<>();
		PigUser sysUser = SecurityUtils.getUser();
		if(sysUser.getUserType() == 6 || sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
		}else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(electricMeter.getEstateId()!=null){
				qw.eq("estate_id",electricMeter.getEstateId());
			}
		}

        if(electricMeter.getConcentratorSn()!=null){
            qw.eq("concentrator_sn",electricMeter.getConcentratorSn());
        }
		if (electricMeter.getMeterType()!=null){
			qw.eq("meter_type",electricMeter.getMeterType());
		}
        TableDataInfo<ElectricMeter> td = PageUtils.buildDataInfo(electricMeterService.page(PageUtils.buildPage(),qw));
        List<ElectricMeter> list = td.getData();
        for (ElectricMeter meter:list){
            EstateRoom estateRoom = estateRoomService.findById(meter.getRoomId());
            if(estateRoom!=null){
				meter.setBuildNo(estateRoom.getBuildNo());
				meter.setUnitNo(estateRoom.getUnitNo());
				meter.setRoomNum(estateRoom.getRoomNum());
			}

			if(StrUtil.isNotEmpty(meter.getQrCode())){
				meter.setQrCode(imgUrl + meter.getQrCode());
			}
        }
        return td;
    }

    /**
     * 导出水电列表
     */
    @ApiOperation("导出水电列表")
    @PreAuthorize("@pms.hasPermission('module:meter:export')")
    @SysLog("水电")
    @GetMapping("/export")
    public List export(@Validated ElectricMeter electricMeter) {
        List<ElectricMeter> list = electricMeterService.list();
        // ExcelUtil<ElectricMeter> util = new // ExcelUtil<ElectricMeter>(ElectricMeter.class);
        return  list;// util.exportExcel(list, "水电");
    }

    /**
     * 获取水电详细信息
     */
    @ApiOperation("获取水电详细信息")
    @PreAuthorize("@pms.hasPermission('module:meter:query')")
    @GetMapping("/{id}")
    public R<ElectricMeter> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ElectricMeter electricMeter = electricMeterService.getById(id);
        return R.ok(electricMeter);
    }


	/**
	 * 获取水电详细信息
	 */
	@ApiOperation("电表清零")
	@PreAuthorize("@pms.hasPermission('module:meter:query')")
	@PostMapping("/clean")
	public R<Void> cleanData(@RequestBody ElectricMeter electricMeter) {
		if(StrUtil.isNotEmpty(electricMeter.getDeviceSn())){
			JSONObject jsonObject = new JSONObject();
			jsonObject.set("sn",electricMeter.getDeviceSn());
			try {
				String resp = OkHttpClientUtil.getInstance().postJson("https://api.sdyuedou.com/ydapi/electric/meter/reset", jsonObject.toString());
				System.out.println("电表清零结果：" + resp);
				if(StrUtil.isNotEmpty(resp)){
					JSONObject jsonObject1 = JSONUtil.parseObj(resp);
					int code = jsonObject1.containsKey("code") ? jsonObject1.getInt("code"):1;
					String msg = jsonObject1.containsKey("msg") ? jsonObject1.getStr("msg"):"";
					if(code == 0){
						return R.okByRow(1);
					}else{
						return R.failed(msg);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return R.okByRow(0);
	}


	/**
	 * 获取水电详细信息
	 */
	@ApiOperation("电表开户")
	@PreAuthorize("@pms.hasPermission('module:meter:query')")
	@PostMapping("/openAccount")
	public R<Void> openAccount(@RequestBody ElectricMeter electricMeter) {
		if(StrUtil.isNotEmpty(electricMeter.getDeviceSn())){
			JSONObject jsonObject = new JSONObject();
			jsonObject.set("sn",electricMeter.getDeviceSn());
			jsonObject.set("init_money",electricMeter.getInitMoney());
			System.out.println("开户请求数据： " + jsonObject);
			try {
				String resp = OkHttpClientUtil.getInstance()
					.postJson("https://api.sdyuedou.com/ydapi/electric/meter/open_account",
						jsonObject.toString());
				System.out.println("电表开户结果：" + resp);
				if(StrUtil.isNotEmpty(resp)){
					JSONObject jsonObject1 = JSONUtil.parseObj(resp);
					int code = jsonObject1.containsKey("code") ? jsonObject1.getInt("code"):1;
					String msg = jsonObject1.containsKey("msg") ? jsonObject1.getStr("msg"):"";
					if(code == 0){
						return R.okByRow(1);
					}else{
						return R.failed(msg);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return R.okByRow(0);
	}


	/**
	 * 获取水电详细信息
	 */
	@ApiOperation("电表余额查询")
	@PreAuthorize("@pms.hasPermission('module:meter:query')")
	@PostMapping("/queryData")
	public R<Void> queryData(@RequestBody ElectricMeter electricMeter) {
		if(StrUtil.isNotEmpty(electricMeter.getDeviceSn())){
			JSONObject jsonObject = new JSONObject();
			jsonObject.set("sn",electricMeter.getDeviceSn());
			jsonObject.set("type",electricMeter.getQueryDataType());
			try {
				String resp = OkHttpClientUtil.getInstance()
					.postJson("https://api.sdyuedou.com/ydapi/electric/meter/query",
						jsonObject.toString());
				System.out.println("余额查询结果：" + resp);
				if(StrUtil.isNotEmpty(resp)){
					JSONObject jsonObject1 = JSONUtil.parseObj(resp);
					int code = jsonObject1.containsKey("code") ? jsonObject1.getInt("code"):1;
					String msg = jsonObject1.containsKey("msg") ? jsonObject1.getStr("msg"):"";
					if(code == 0){
						return R.okByRow(1);
					}else{
						return R.failed(msg);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return R.okByRow(0);
	}


	/**
	 * 线下充值
	 */
	@ApiOperation("线下充值")
	@PreAuthorize("@pms.hasPermission('module:order:recharge')")
	@PostMapping("/recharge")
	public R<Void> recharge(@Valid @RequestBody ElectricMeter electricMeter) {
		if(electricMeter.getRechargeMoney() > 0){
			return R.okByRow(electricOrderService.addOrder(electricMeter));
		}
		return R.failed("充值金额必须大于0");
	}


	/**
     * 新增水电
     */
    @ApiOperation("新增水电")
    @PreAuthorize("@pms.hasPermission('module:meter:add')")
    @SysLog("水电")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody ElectricMeter electricMeter) {
		if(electricMeter.getPropertyId()!=null){
			Property property=propertyService.findById(electricMeter.getPropertyId());
			electricMeter.setPropertyName(property.getPropertyName());
		}
		if (electricMeter.getMeterType()==1){
			if (electricMeter.getDeviceSn()!=null)
			electricMeter.setConcentratorSn(electricMeter.getDeviceSn());
		}
		if (electricMeter.getBangType()!=0){
			EstateRoom estateRoom = estateRoomService.findById(electricMeter.getRoomId());
			if(estateRoom!= null){
				electricMeter.setRoomNo(estateRoom.getRoomNo());
				electricMeter.setHolderName(estateRoom.getRealName());
				electricMeter.setHolderPhone(estateRoom.getPhoneNum());
				electricMeter.setEstateId(estateRoom.getEstateId());
				electricMeter.setEstateName(estateRoom.getEstateName());
			}
		}
        electricMeter.setAccountMoney(BigDecimal.valueOf(0.00));
        electricMeter.setElectricityCount(BigDecimal.valueOf(0.00));
        electricMeter.setCreateTime(new Date());
        electricMeter.setLastQueryTime(new Date());
        electricMeter.setLastWarnTime(new Date());
        electricMeter.setWarnTipOne(new BigDecimal(30));//1级预警值
        electricMeter.setWarnTipTwo(new BigDecimal(5));//2级预警值
        return R.okByRow(electricMeterService.save(electricMeter) ? 1 : 0);
    }

    /**
     * 修改水电
     */
    @ApiOperation("修改水电")
    @PreAuthorize("@pms.hasPermission('module:meter:edit')")
    @SysLog("水电")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody ElectricMeter electricMeter) {
		if (electricMeter.getBangType()!=0){
			EstateRoom estateRoom=estateRoomService.findById(electricMeter.getRoomId());
			if(estateRoom!= null){
				electricMeter.setRoomNo(estateRoom.getRoomNo());
				electricMeter.setHolderName(estateRoom.getRealName());
				electricMeter.setHolderPhone(estateRoom.getPhoneNum());
				electricMeter.setEstateId(estateRoom.getEstateId());
				electricMeter.setEstateName(estateRoom.getEstateName());
			}else if (electricMeter.getEstateId()!=null){
				Estate estate=estateService.findById(electricMeter.getEstateId());
				electricMeter.setEstateName(estate.getEstateName());
			}
		}else {
			electricMeter.setRoomNo(null);
			electricMeter.setHolderName(null);
			electricMeter.setHolderPhone(null);
			electricMeter.setRoomId(null);
			Estate estate=estateService.findById(electricMeter.getEstateId());
			electricMeter.setEstateName(estate.getEstateName());
		}

		if (electricMeter.getMeterType()==1){
			if (electricMeter.getDeviceSn()!=null)
				electricMeter.setConcentratorSn(electricMeter.getDeviceSn());
		}
        return R.okByRow(electricMeterService.updateById(electricMeter) ? 1 : 0);
    }

    /**
     * 删除水电
     */
    @ApiOperation("删除水电")
    @PreAuthorize("@pms.hasPermission('module:meter:remove')")
    @SysLog("水电")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(electricMeterService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


/*
	*//**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:estate:edit')")
	public R<Void> resetQrCode(@RequestBody ElectricMeter electricMeter) {
		if(electricMeter.getId()!=null){
			try{
				electricMeter = electricMeterService.getById(electricMeter.getId());
				String qrCode = "";
				String fileName = "electric_meter" + electricMeter.getId() + ".jpg";
				String content = "123456789" + electricMeter.getId();
				int upload_type = 0;//FileUploadUtils.TYPE_ESTATE_PHOTOS;
				System.out.println("content:  "+ content);
				String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;

				QRCodeUtilEx.createQrCodeImg(content, electricMeter.getEstateName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
				qrCode = img_key;
				electricMeter.setQrCode(qrCode);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (electricMeterService.updateById(electricMeter)) {
				return R.ok();
			}
		}
		return R.failed();
	}

}
